//请求拦截器

import 'dart:math';

import 'package:dio/dio.dart';
import 'package:get/get.dart' hide Response;
import 'package:oi_ai_tool/config/app_config.dart';
import 'package:oi_ai_tool/config/response_type.dart';
import 'package:oi_ai_tool/services/user_service.dart';
import 'package:oi_ai_tool/util/http/oi_response.dart';
import 'package:oi_ai_tool/util/oi_logger.dart';

class HttpIntercept extends Interceptor {
  @override
  void onRequest(RequestOptions options, RequestInterceptorHandler handler) {
    var userService = Get.find<UserService>();
    //print("token: ${userService.token?.value}");
    options.headers.addAll({
      'Authorization': userService.token,
      'Version_code': AppConfig.versionCode,
      'Version': AppConfig.versionName,
      'content_type': OiResponseType.JSON,
      // 'Platform': 'Android', //DeviceUtil.getPlatformEnum().name,
      // 'Language': Get.find<ProfileViewModel>().state.locale.languageKey,
      'X-B3-TraceId':
          "${Random().nextInt(100000)}-${DateTime.now().millisecondsSinceEpoch}",
    });
      super.onRequest(options, handler);
  }

  @override
  void onResponse(Response response, ResponseInterceptorHandler handler) {
    String type = response.headers.value("content-type")!;
    OiLogger.info(msg: "---------content-type:$type");
    if (type.contains(OiResponseType.EVENT_STREAM)) {
      handler.next(response);
    } else if (type.contains(OiResponseType.JSON)) {
      final data = response.data;
      final commonResult = CommonResult.from(data);
      response.data = commonResult;
      if (commonResult.isSuccess) {
        handler.next(response);
      } else {
        throw commonResult;
      }
    }
    // super.onResponse(response, handler);
  }
}
